import React, { useState, useRef, useEffect, useCallback } from 'react';
import { Button, Input, Typography, Row, Col, message } from 'antd';
import { sendChatMessage } from '../../config/api/home';
import { useAutoScroll } from '../../utils/useAutoScroll';

const { TextArea } = Input;
const { Title } = Typography;

const EmailGenerator = (props) => {
  console.log('WriteEmail props:', props);
  const [selectedType, setSelectedType] = useState('发送祝贺');
  const [inputContent, setInputContent] = useState('');
  const [generatedContent, setGeneratedContent] = useState('');
  const [isGenerating, setIsGenerating] = useState(false);

  // 用于获取Antd TextArea真实DOM节点
  const textAreaRef = useRef(null);
  const contentRef = useRef(null);

  // 打字机相关
  const currentIndexRef = useRef(0);
  const timeoutId = useRef(null);
  const fullTextRef = useRef('');
  const isTypingRef = useRef(false);

  // 自动滚动到底部
  useEffect(() => {
    if (contentRef.current) {
      contentRef.current.scrollTop = contentRef.current.scrollHeight;
    }
  }, [generatedContent]);

  useAutoScroll({
    enabled: true,
    scrollBehavior: 'smooth',
    getNode: () => textAreaRef.current?.resizableTextArea?.textArea || null
  });

  const emailTypes = [
    '发送祝贺',
    '邀请参会',
    '跟进事件',
    '通知',
    '计划',
    '人员介绍'
  ];

  const handleTypeSelect = (type) => {
    setSelectedType(type);
  };

  // 打字机动画
  const updateContent = useCallback(() => {
    const data = fullTextRef.current;
    if (currentIndexRef.current < data.length) {
      let currentChar = data[currentIndexRef.current];
      if (currentChar !== undefined) {
        setGeneratedContent(prev => {
          const newContent = prev + currentChar;
          setTimeout(() => {
            if (contentRef.current) {
              contentRef.current.scrollTop = contentRef.current.scrollHeight;
            }
          }, 0);
          return newContent;
        });
      }
      currentIndexRef.current += 1;
      timeoutId.current = setTimeout(() => {
        updateContent();
      }, 30);
    } else {
      isTypingRef.current = false;
      timeoutId.current = null;
    }
  }, []);

  // 流式发送消息
  const sendMessage = useCallback(
    async (sendText) => {
      try {
        currentIndexRef.current = 0;
        setGeneratedContent('');
        fullTextRef.current = '';
        isTypingRef.current = false;
        if (timeoutId.current) {
          clearTimeout(timeoutId.current);
          timeoutId.current = null;
        }
        const headers = {
          Authorization: "Bearer " + (props.dataObj?.bot_id || ''),
          "Content-Type": "application/json",
        };
        const requestData = {
          "inputs": {},
          "query": sendText,
          "response_mode": "streaming",
          "conversation_id": '',
          "user": "user11",
        };
        const response = await fetch('https://zhi1develop.zicp.fun/v1/chat-messages', {
          method: 'POST',
          headers: headers,
          body: JSON.stringify(requestData),
        });
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let fullText = '';
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
          const chunk = decoder.decode(value, { stream: true });
          const lines = chunk.split('\n').filter(line => line.trim() !== '');
          for (const line of lines) {
            if (line.startsWith('data: ')) {
              try {
                const data = JSON.parse(line.substring(6));
                if (data.answer || data.message) {
                  const newContent = data.answer || data.message || '';
                  fullText += newContent;
                  fullTextRef.current = fullText;
                  if (!isTypingRef.current) {
                    isTypingRef.current = true;
                    updateContent();
                  }
                }
              } catch (e) {
                console.error('Error parsing SSE data:', e);
              }
            }
          }
        }
      } catch (error) {
        console.error("Error sending message:", error);
        setGeneratedContent('生成失败，请重试。');
      }
    },
    [props.dataObj, updateContent]
  );

  // 生成按钮
  const handleGenerate = async () => {
    if (!inputContent.trim()) {
      message.error('邮件主题不能为空');
      return;
    }
    setIsGenerating(true);
    setGeneratedContent('');
    message.loading('生成内容中，请稍后...', 2);
    await sendMessage(`${selectedType}: ${inputContent}`);
    setIsGenerating(false);
    message.success('内容生成成功');
  };

  const handleCopy = () => {
    if (generatedContent) {
      navigator.clipboard.writeText(generatedContent);
      message.success('复制成功');
    } else {
      message.warning('没有内容可复制');
    }
  };

  return (
    <div style={{ 
      padding: '20px 50px',
      height: 'calc(100vh - 127px)', // 减去底部间距
      display: 'flex',
      flexDirection: 'column'
    }}>
      <Title level={5} style={{ fontSize: '16px', marginBottom: '20px', fontWeight: 'bold' }}>智能撰写</Title>
      
      {/* 邮件类型选择按钮 */}
      <div style={{ marginBottom: '20px' }}>
        {emailTypes.map(type => (
          <Button 
            key={type}
            style={{ 
              height: '40px',
              marginRight: '10px',
              borderRadius: '4px',
              borderColor: selectedType === type ? '#1890ff' : '#d9d9d9',
              color: selectedType === type ? '#1890ff' : 'rgba(0, 0, 0, 0.65)',
              backgroundColor: 'white',
              boxShadow: 'none',
              padding: '0 15px',
              fontSize: '14px'
            }}
            onClick={() => handleTypeSelect(type)}
          >
            {type}
          </Button>
        ))}
      </div>
      
      <div style={{ marginBottom: '20px' }}>
        <div style={{ marginBottom: '10px', fontSize: '14px', color: 'rgba(0, 0, 0, 0.65)' }}>
          请描述您的邮件主题，邮件目的及关键内容要点:
        </div>
        <TextArea 
          rows={6} 
          value={inputContent}
          onChange={(e) => setInputContent(e.target.value)}
          style={{ 
            marginTop: '5px',
            resize: 'none',
            border: '1px solid #d9d9d9',
            borderRadius: '2px',
            padding: '10px'
          }}
        />
      </div>
      
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', marginBottom: '50px' }}>
        <Row align="middle" style={{ marginBottom: '10px' }}>
          <Col>
            <span style={{ fontSize: '14px', color: 'rgba(0, 0, 0, 0.65)' }}>生成邮件:</span>
          </Col>
          <Col>
            <Button 
              size="small" 
              style={{ 
                marginLeft: '10px', 
                borderColor: '#1890ff',
                color: '#1890ff',
                backgroundColor: 'white',
                borderRadius: '4px',
                fontSize: '12px',
                height: '24px',
                padding: '0 8px'
              }}
              onClick={handleCopy}
            >
              复制内容
            </Button>
          </Col>
          <Col>
            <Button 
              size="small" 
              loading={isGenerating}
              style={{ 
                marginLeft: '10px', 
                borderColor: '#52c41a',
                color: isGenerating ? 'rgba(0, 0, 0, 0.25)' : '#52c41a',
                backgroundColor: 'white',
                borderRadius: '4px',
                fontSize: '12px',
                height: '24px',
                padding: '0 8px'
              }}
              onClick={handleGenerate}
              disabled={isGenerating}
            >
              {isGenerating ? '生成中...' : '生成内容'}
            </Button>
          </Col>
        </Row>
        <TextArea
          ref={textAreaRef}
          rows={12}
          value={generatedContent}
          onChange={(e) => setGeneratedContent(e.target.value)}
          style={{
            flex: 1,
            resize: 'none',
            border: '1px solid #d9d9d9',
            borderRadius: '2px',
            padding: '10px',
            overflowY: 'auto',
            backgroundColor: 'white',
            fontFamily: 'inherit',
            whiteSpace: 'pre-wrap',
            minHeight: '400px'
          }}
          onScroll={(e) => {
            if (contentRef.current) {
              contentRef.current.scrollTop = e.target.scrollTop;
            }
          }}
        />
      </div>
    </div>
  );
};

export default EmailGenerator;